package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

public class FriendApiImpl implements FriendApi{
    @Autowired
    private MongoTemplate mongoTemplate;
//   添加好友
    @Override
    public void save(Long userId, Long friendId) {
        //1.构建查询条件
        Criteria criteria=Criteria.where("userId").is(userId).and("friendId").is(friendId);
        Query query=Query.query(criteria);
        //从数据库获取查询结果
        boolean exists = mongoTemplate.exists(query, Friend.class);
        if (!exists){//不存在,建立
            Friend friend=new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        //存在,好友建立关系
        Criteria criteria1=Criteria.where("userId").is(friendId).and("friendId").is(userId);
        Query query1=Query.query(criteria1);
        boolean exists1 = mongoTemplate.exists(query1, Friend.class);
        if (!exists1){//不存在,建立
            Friend friend1=new Friend();
            friend1.setUserId(friendId);
            friend1.setFriendId(userId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
    }
        /*好友列表分页*/
    @Override
    public List<Friend> findByUserId(Long userId, Integer page, Integer pagesize) {
       Query query=Query.query(Criteria.where("userId").is(userId))
               .skip((page-1)*pagesize).limit(pagesize)
               .with(Sort.by(Sort.Order.desc("created")));
        return mongoTemplate.find(query,Friend.class);
    }
}
